/* Copyright (c) 2016-2020 Enfry Ltd. All Rights Reserved.
 * 
 * This software is the confidential and proprietary information of Enfry. 
 * You shall not disclose such Confidential Information
 * and shall use it only in accordance with the terms of the agreements
 * you entered into with Enfry.
 */
package com.enfry.common.util;

import com.enfry.common.util.constants.RegexpConstants;
import com.enfry.common.util.validate.Validates;

/**
 * 
 * <请简单说明此类用途>
 * 
 * @Title com.enfry.util.Replaces
 * @author Penghu
 * @date 2018年1月4日
 */
public class Replaces implements RegexpConstants {
	/**
	 * 替换单引号'成\'
	 * 
	 * @param str 原字符串
	 * @return 新字符串
	 */
	public static String replaceQuotation(String str) {
		if (Validates.isEmpty(str))
			return str;

		return str.replaceAll("\'", "\\\\\'");
	}

	/**
	 * 替换单引号"成\"
	 * 
	 * @param str 原字符串
	 * @return 新字符串
	 */
	public static String replaceDoubleQuotation(String str) {
		if (Validates.isEmpty(str))
			return str;

		return str.replaceAll("\"", "\\\\\"");
	}

	/**
	 * 替换反斜杠\成指定的字符
	 * 
	 * @param str 原字符串
	 * @param replacement \替换成后字符串
	 * @return 新字符串
	 */
	public static String replaceBackslash(String str, String replacement) {
		return replaceAllEscape(str, "\\", replacement);
	}

	/**
	 * 替换字符串regex成replacement，注意这里会对regex全正则表达式字符转义后再替换
	 * 
	 * @param src 原字符串
	 * @param regex 要替换的字符串
	 * @param replacement 替换成新的字符串
	 * @return 替换
	 */
	public static String replaceAllEscape(String str, String regex, String replacement) {
		if (Validates.isEmpty(str))
			return str;

		// 对被替换字符进行转义
		StringBuilder strb = new StringBuilder();
		for (int i = 0; i < regex.length(); i++) {
			char c = regex.charAt(i);
			if (Validates.isCharInString(c, ESCAPE))
				strb.append("\\");

			strb.append(c);
		}
		regex = strb.toString();

		// 对替换后字符进行转义
		strb = new StringBuilder();
		for (int i = 0; i < replacement.length(); i++) {
			char c = replacement.charAt(i);
			if (Validates.isCharInString(c, ESCAPE))
				strb.append("\\");

			strb.append(c);
		}
		replacement = strb.toString();

		// 最后再作替换
		return str.replaceAll(regex, replacement);
	}

	/**
	 * 把要替换的字符串进行转义检查，得到转义后的字符
	 * 
	 * @param replace 要转义的字符串
	 * @return 转义后的字符串
	 */
	public static String toReplaceEscape(String replace) {
		StringBuilder strb = new StringBuilder();
		for (int i = 0; i < replace.length(); i++) {
			char c = replace.charAt(i);
			if (Validates.isCharInString(c, ESCAPE))
				strb.append("\\");

			strb.append(c);
		}

		return strb.toString();
	}
}
